package com.pfzy.utildemo.utils;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import java.util.HashMap;

public class NotificationChannelUtil {
    public static final String DEFAULT_CHANNEL_ID = "default";
    private static final String DEFAULT_CHANNEL_NAME = "默认";
    private static HashMap<String, NotificationChannel> mChannelList;

    /**
     * 获取默认通知频道ID
     */
    public static NotificationChannel getDefaultNotificationChannelId(Context context) {
        return getNotificationChannelId(context, DEFAULT_CHANNEL_ID, DEFAULT_CHANNEL_NAME);
    }

    /**
     * 获取通知频道ID
     */
    public static NotificationChannel getNotificationChannelId(Context context, String channelId, String channelName) {
        NotificationChannel channel = initNotificationChannel(context, channelId, channelName);
        return channel;
    }

    /**
     * 初始化通知频道ID
     *
     * @return
     */
    private static NotificationChannel initNotificationChannel(Context context, String channelId, String channelName) {
        if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (mChannelList == null) {
                mChannelList = new HashMap<>();
            }
            NotificationChannel channel = mChannelList.get(channelId);
            if (channel == null) {
                NotificationChannel defaultChannel = createNotificationChannel(context.getApplicationContext(), channelId, channelName, 3);
                mChannelList.put(channelId, defaultChannel);
                return defaultChannel;
            }
            return channel;
        }
        return null;
    }

    /**
     * 创建通知频道ID
     */
    private static NotificationChannel createNotificationChannel(Context context, String channelId, String channelName, int importance) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager == null) {
            return null;
        }
        NotificationChannel channel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel = new NotificationChannel(channelId, channelName, importance);
            manager.createNotificationChannel(channel);
        }
        return channel;
    }
}
